const express = require('express')
const ioredis = require('ioredis')

const app = express()

const redis = new ioredis({
  port: 6379,
  host: '127.0.0.1',
  // 用于调试阶段
  // showFriendlyErrorStack: true
})

app.use(express.json())

// 存放到 set 中, 获取时 随机获取一个值,并且移除该值
app.get('/', async (req, res, next) => {
  try {
    const { user, type = 'all' } = req.query
    if (!user) {
      next({ message: 'user is required' })
    }
    const pipeline = redis.multi()

    if (type === 'all') {
      pipeline.spop('all').exec((err, ret) => {
        const member = ret[0][1]
        if (err || !member) {
          next({ message: '你捡到一颗✨了' })
          return
        }
        pipeline.srem(JSON.parse(member).type, member).exec((err1, ret1) => {
          if (err1) {
            next({ message: '你捡到一颗✨了' })
            return
          }
        })
        res.json({
          code: 1,
          msg: JSON.parse(member),
        })
      })
    } else if (type === 'male' || type === 'female') {
      pipeline.spop(type).exec((err, ret) => {
        const member = ret[0][1]
        if (err || !member) {
          next({ message: '你捡到一颗✨了' })
          return
        }
        pipeline.srem('all', member).exec((err1, ret1) => {
          if (err1) {
            next({ message: '你捡到一颗✨了' })
            return
          }
        })
        res.json({
          code: 1,
          msg: JSON.parse(member),
        })
      })
    } else {
      next({ message: 'type is unlawfulness' })
      return
    }
  } catch (error) {
    next(err)
    return
  }
})

// 扔漂流瓶
app.post('/', async (req, res, next) => {
  const multi = redis.multi()
  try {
    const { time = Date.now(), owner, type, content } = req.query
    if (!owner || !type || !content) {
      next({ message: 'missing required params' })
    }
    if (!['string', 'number'].includes(typeof owner)) {
      next({ message: 'owner must only one' })
    }
    if (!['male', 'female'].includes(type)) {
      next({ message: 'type value of male or female' })
    }
    if (typeof time !== 'number') {
      next({ message: 'time type must number' })
    }
    if (content.length > 150) {
      next({ message: 'content maxLength 150' })
    }
    const drifter = {
      time,
      owner,
      type,
      content,
    }
    const add = multi
      .sadd('all', JSON.stringify(drifter))
      .sadd(type, JSON.stringify(drifter))
      .exec((err, ret) => {
        if (err) {
          next(err)
        }
        res.json({
          code: 1,
          msg: 'success',
        })
      })
  } catch (error) {
    next(error)
  }
})

app.use((err, req, res, next) => {
  res.json({
    code: 0,
    msg: err.message,
  })
})

app.listen('3113', () => {
  console.log('app is running port 3113...')
})
